// ********************************
// 爬取网易云音乐飙升榜，榜一的10页评论
const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        ignoreDefaultArgs: ['--enable-automation'],
        defaultViewport: {
            width: 1200,
            height: 900
        }
    })
    const page = await browser.newPage()
    // 网易云音乐飙升榜
    await page.goto('https://music.163.com/#/discover/toplist', { waitUntil: "networkidle0" })
    // 页面内部的 frame
    const contentFrame1 = await page.frames().find(f => f.name() === 'contentFrame');
    await contentFrame1.click('tr:first-child span.txt > a')
    let musics = []
    for (let i = 0; i < 10; i++) {
        await contentFrame1.waitFor("div.itm")
        const temp = await contentFrame1.evaluate(() => {
            var list = [...document.querySelectorAll('div.itm')]
            return list.map(el => {
                const avatar = el.querySelector("a > img").src
                const profile = el.querySelector(".cnt a").href
                const nickname = el.querySelector(".cntwrap .s-fc7").textContent
                const content = el.querySelector(".cnt").textContent.replace(nickname + "：", "")
                const createTime = el.querySelector(".rp div.time").textContent;
                const likesCount = el.querySelector(".rp a").textContent.trim();
                return { avatar, profile, nickname, content, createTime, likesCount };
            })
        })
        musics = musics.concat(temp);
        await contentFrame1.waitFor('.znxt')
        await contentFrame1.click('.znxt')
    }
    fs.writeFileSync("./data.json", JSON.stringify(musics))

    // await browser.close()
})()